package model

import (
	"errors"
	"gorm.io/datatypes"
	"gorm.io/gorm"
	"time"
)

// 完成
type (
	TaskLogMoodle struct {
		db *gorm.DB
	}
	TaskLog struct {
		ID         string         `gorm:"type:varchar(40);primaryKey" json:"id"`
		CreatedAt  Datetime       `json:"created_at"`
		UpdatedAt  Datetime       `json:"updated_at"`
		StationId  string         `gorm:"type:varchar(40);index;"json:"station_id"`
		ThingId    string         `gorm:"type:varchar(40); index;"json:"thing_id"`
		TaskName   string         `gorm:"type:varchar(32); default:''"json:"task_name"`
		TaskType   string         `gorm:"type:varchar(32)" json:"task_type"`                  // 任务类型
		PlanType   string         `gorm:"type:varchar(16);index;default:''" json:"plan_type"` // 计划类型  // manual 手动计划, day 日计划， week 周计划， month 月计划
		Content    datatypes.JSON `json:"content"`
		Status     int            `gorm:"type:int; default:0"json:"status"`   // 0 初始状态, 1 成功, 2 失败, 3 休眠状态
		TaskStatus string         `gorm:"type:varchar(6)" json:"task_status"` // doing 运行中 done 完成，sleep 休眠状态
		ProcessNum int            `gorm:"default:0" json:"process_num"`       // 任务进程数量
		CurrNum    int            `gorm:"default:0" json:"curr_num"`          // 当前一执行的进程数量
		Msg        string         `gorm:"type:text"json:"msg"`
		Pid        string         `gorm:"type:varchar(40);index;default:''" json:"pid"`
	}

	ContentJson struct {
		Msg         string               `json:"msg"`
		Code        int                  `json:"code"`
		RequestId   string               `json:"request_id"`
		Value       string               `json:"value"`
		RawValue    interface{}          `json:"raw_value"`
		CollectData map[string][]float64 `json:"collect_data"`
		ModelId     string               `json:"model_id"`
		TaskType    string               `json:"task_type"`
		StationId   string               `json:"station_id"`
		TaskParams  struct {
			Ext       int           `json:"ext"`
			Unit      string        `json:"unit"`
			Number    int           `json:"number"`
			GasType   int           `json:"gas_type"`
			ValueTime []interface{} `json:"value_time"`
		} `json:"task_params"`
	}
)

func NewTaskLogMoodle(db *gorm.DB) *TaskLogMoodle {
	return &TaskLogMoodle{
		db,
	}
}

func (m *TaskLogMoodle) Find(id string) (TaskLog, error) {
	var data TaskLog
	err := m.db.Where("id = ?", id).Model(&TaskLog{}).First(&data).Error
	return data, err
}
func (m *TaskLogMoodle) Add(data TaskLog) (string, error) {
	data.CreatedAt = Datetime(time.Now())
	data.UpdatedAt = Datetime(time.Now())
	err := m.db.Create(&data).Error
	return data.ID, err
}

func (m *TaskLogMoodle) Update(id string, data TaskLog) error {
	data.UpdatedAt = Datetime(time.Now())
	return m.db.Where("id = ?", id).Updates(&data).Error
}

func (m TaskLogMoodle) FindLogCount(stationId string, planType string) (int64, error) {
	var total int64
	dbSession := m.db.Model(&TaskLog{})
	dbSession.Where("station_id = ?", stationId)
	dbSession.Where("pid =''")
	if planType != "" {
		dbSession.Where("plan_type = ?", planType)
	}
	err := dbSession.Count(&total).Error
	return total, err
}

func (m *TaskLogMoodle) FindLogList(stationId string, page, size int, planType string) ([]TaskLog, error) {
	var resp []TaskLog
	dbSession := m.db.Model(&TaskLog{})
	dbSession.Where("station_id = ?", stationId)
	dbSession.Where("pid =''")
	if planType != "" {
		dbSession.Where("plan_type = ?", planType)
	}
	err := dbSession.Limit(size).Offset((page - 1) * size).Order("created_at desc").Find(&resp).Error
	if errors.Is(err, gorm.ErrRecordNotFound) {
		return []TaskLog{}, nil
	}
	if err != nil {
		return nil, err
	}
	return append([]TaskLog{}, resp...), nil
}

func (m *TaskLogMoodle) QuerySubTaskLog(pid []string) ([]TaskLog, error) {
	var resp []TaskLog
	dbSession := m.db.Model(&TaskLog{})
	dbSession.Where("pid in ?", pid)
	err := dbSession.Order("created_at asc").Find(&resp).Error
	if errors.Is(err, gorm.ErrRecordNotFound) {
		return []TaskLog{}, nil
	}
	if err != nil {
		return nil, err
	}
	return resp, nil
}
